using Microsoft.Extensions.DependencyInjection;
using SeataNet.Core.Configuration;
using SeataNet.Core.RPC;
using SeataNet.Core.Services;
using SeataNet.Core.Transaction;

namespace SeataNet.Core.DependencyInjection
{
    /// <summary>
    /// Seata服务集合扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Seata服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configurationAction">配置操作</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSeata(this IServiceCollection services, Action<SeataConfiguration>? configurationAction = null)
        {
            // 配置Seata
            var configuration = SeataConfiguration.Instance;
            configurationAction?.Invoke(configuration);
            
            // 注册核心服务
            services.AddSingleton<IRpcClient, DefaultRpcClient>();
            services.AddSingleton<ITransactionManager, DefaultTransactionManager>();
            services.AddSingleton<IResourceManager, DefaultResourceManager>();
            services.AddSingleton<ISeataService, SeataService>();
            
            // 注册配置
            services.AddSingleton(configuration);
            
            return services;
        }
        
        /// <summary>
        /// 添加Seata服务（带配置）
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSeata(this IServiceCollection services, SeataConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            
            // 更新配置
            SeataConfiguration.Instance.Update(configuration);
            
            // 注册核心服务
            services.AddSingleton<IRpcClient, DefaultRpcClient>();
            services.AddSingleton<ITransactionManager, DefaultTransactionManager>();
            services.AddSingleton<IResourceManager, DefaultResourceManager>();
            services.AddSingleton<ISeataService, SeataService>();
            
            // 注册配置
            services.AddSingleton(configuration);
            
            return services;
        }
    }
}